package com.app.reptile.tasks;

import com.app.reptile.base.MybatisSingleton;
import com.app.reptile.base.SchedulerSingleton;
import com.app.reptile.constant.JobAnnotation;
import com.app.reptile.constant.JobType;
import com.app.reptile.utils.ClassUtil;
import com.mybatis.mapper.SysConfigMapper;
import com.mybatis.pojo.SysConfig;
import org.apache.ibatis.session.SqlSession;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

public class AllRunTasks {

	private Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * 定时刷新调度线程池
	 */
//    private static final ScheduledExecutorService EXECUTORS = new ScheduledThreadPoolExecutor(8, new ThreadFactoryBuilder().setNameFormat("refresh-showdata-pool-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());
	private SysConfigMapper sysConfigMapper;
	private SqlSession sqlSession;

	public void setSqlSession(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}

	public SqlSession getSqlSession() {
		return sqlSession;
	}

	public AllRunTasks() {
		sqlSession = MybatisSingleton.getInstance().getSqlSession();
		this.sysConfigMapper = sqlSession.getMapper(SysConfigMapper.class);
	}

	// * * * * * * *
	// 格式： [秒] [分] [小时] [日] [月] [周] [年]

	public void run() throws Exception {

		List<Class<?>> list = ClassUtil.getAllClassByInterface(AbstractTask.class);

		List<SysConfig> configs = sysConfigMapper.selectListByType(JobType.JOB.getValue());
		for(Class<?> clazz : list){
			JobAnnotation jobAnnotation = clazz.getAnnotation(JobAnnotation.class);
			if (Objects.isNull(jobAnnotation)){
				continue;
			}
			String value = jobAnnotation.value();
			String name = clazz.getName();
			boolean sure = false;
			for(SysConfig sysConfig : configs){
				if (name.equals(sysConfig.getName())){
					sure = true;
					break;
				}
			}

			if (!sure){
				SysConfig bean = new SysConfig();
				bean.setType(JobType.JOB.getValue());
				bean.setName(name);
				bean.setValue(value);
				bean.setDelFlag(Boolean.FALSE);

				bean.setIsDisable(!"com.app.reptile.tasks.JobService".equals(name));
				sysConfigMapper.insert(bean);
			}
		}

		configs = sysConfigMapper.selectListByType(JobType.JOB.getValue());
		// 定时器对象
		Scheduler scheduler = SchedulerSingleton.getInstance();
		for (SysConfig config : configs) {
			String name = config.getName();
			boolean sure = false;
			try{
				Object object = Class.forName(name).newInstance();
				Class<?>[] classes = object.getClass().getSuperclass().getInterfaces();
				for (Class<?> clazz : classes) {
					if ("org.quartz.Job".equals(clazz.getName())) {
						sure = true;
						break;
					}
				}

				if (sure && !config.getDelFlag() && !config.getIsDisable()) {

					Class<? extends Job> jobClazz = (Class<? extends Job>) Class.forName(name);

					JobDetail job = JobBuilder.newJob(jobClazz).withIdentity(config.getName(), config.getType()).build();

					Trigger trigger = TriggerBuilder.newTrigger().withIdentity(config.getName(), config.getType()).withSchedule(CronScheduleBuilder.cronSchedule(config.getValue())).startNow().build();

					scheduler.scheduleJob(job, trigger);
				}
			}catch (Exception e){
				logger.error("fail load class", e);
			}
		}
		scheduler.start();
	}
}
